package com.jk1.bianligou.blg.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jk1.bianligou.blg.common.ErrorCode;
import com.jk1.bianligou.blg.domain.constant.OrderStatus;
import com.jk1.bianligou.blg.domain.dto.order.CreateOrderRequest;
import com.jk1.bianligou.blg.domain.po.Item;
import com.jk1.bianligou.blg.domain.po.Order;
import com.jk1.bianligou.blg.domain.po.OrderItem;
import com.jk1.bianligou.blg.domain.vo.OrderVO;
import com.jk1.bianligou.blg.exception.BizException;
import com.jk1.bianligou.blg.mapper.OrderMapper;
import com.jk1.bianligou.blg.service.ItemService;
import com.jk1.bianligou.blg.service.OrderItemService;
import com.jk1.bianligou.blg.service.OrderService;
import com.jk1.bianligou.blg.utils.UserUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.jk1.bianligou.blg.domain.constant.ItemStatus.ON_SALE;

/**
 * @author WHH
 * @description 针对表【order(订单表)】的数据库操作Service实现
 * @createDate 2025-04-11 21:58:04
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order>
        implements OrderService {

    @Resource
    private OrderItemService orderItemService;
    @Resource
    private ItemService itemService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createOrder(CreateOrderRequest request, HttpServletRequest httpServletRequest) {
        Long itemId = request.getItemId();
        String itemName = request.getItemName();
        BigDecimal currentPrice = request.getCurrentPrice();
        Integer quantity = request.getQuantity();
        BigDecimal totalPrice = request.getTotalPrice();
        BigDecimal deliveryFee = request.getDeliveryFee();
        String deliveryAddress = request.getDeliveryAddress();
        String contactPhone = request.getContactPhone();
        String remark = request.getRemark();
        //获取对应商品
        Item item = itemService.getById(itemId);
        //检查库存
        if (item.getStatus() != ON_SALE || item.getStock() < quantity) {
            throw new BizException(ErrorCode.PARAMS_ERROR, "该商品库存不足或已下架！");
        }
        //库存充足
        //使用乐观锁扣减库存
        boolean success = itemService.update()
                .eq("id", itemId)
                .eq("stock", item.getStock())
                .setSql("stock = stock - " + quantity)
                .update();
        if (success) {
            //创建订单
            Order order = new Order();
            order.setTotalAmount(totalPrice);
            order.setActualAmount(currentPrice);
            order.setDeliveryAddress(deliveryAddress);
            order.setDeliveryFee(deliveryFee);
            order.setContactPhone(contactPhone);
            order.setRemark(remark);
            order.setStatus(OrderStatus.DEFAULT);
            order.setUserId(UserUtils.getLoginUserId(httpServletRequest));
            save(order);
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(order.getId());
            orderItem.setItemName(itemName);
            orderItem.setItemId(itemId);
            orderItem.setQuantity(quantity);
            orderItem.setTotalPrice(currentPrice);
            orderItem.setCurrentPrice(currentPrice);
            orderItemService.save(orderItem);
            return order.getId();
        } else {
            throw new BizException(ErrorCode.SYSTEM_ERROR, "订单创建失败!");
        }
    }

    @Override
    public List<OrderVO> getByUserId(Long id) {
        List<Order> orders = list(new QueryWrapper<Order>().eq("user_id", id));
        if (CollectionUtil.isEmpty(orders)) {
            return null;
        }
        return orders.stream()
                .map(order -> BeanUtil.copyProperties(order, OrderVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public Boolean markSuccess(Long id) {
        Order order = getById(id);
        order.setStatus(OrderStatus.COMPLETE);
        order.setCompleteTime(new Date());
        return updateById(order);
    }

    @Override
    public Map<Integer, List<OrderVO>> showOrders() {
        List<Order> list = list();
        return list.stream()
                .map(order -> BeanUtil.copyProperties(order, OrderVO.class))
                .collect(Collectors.groupingBy(OrderVO::getStatus));
    }
}




